#include "common.h"

#define DEFAULT_ENTRY ((void *)0x8048000)

extern int fs_open(const char *pathname, int flags, int mode);
extern ssize_t fs_read(int fd, void *buf, size_t len);
extern ssize_t fs_write(int fd, void *buf, size_t len);
extern int fs_close(int fd);
extern size_t fs_filesz(int fd);
off_t fs_lseek(int fd, off_t offset,int whence);
void* new_page(void);

uintptr_t loader(_Protect *as, const char *filename) {
    printf("Loading file: %s\n", filename);
    int fd = fs_open(filename, 0, 0);
    size_t filesize = fs_filesz(fd);
    size_t npages = (filesize + PGSIZE - 1) / PGSIZE;  // 计算页面数
    for (size_t i = 0; i < npages; ++i) {
        // 申请一页物理内存
        void *pa = new_page();
        // 计算虚拟地址
        void * va = DEFAULT_ENTRY + i * PGSIZE;
        _map(as, va, pa);
        // 计算本次读取的字节数
        size_t bytes_to_read = PGSIZE;
        if (i == npages - 1) {
            bytes_to_read = filesize - i * PGSIZE;
        }
        // 从文件读取一页内容到物理页
        fs_lseek(fd, i * PGSIZE, 0);
        fs_read(fd, pa, bytes_to_read);
    }
    fs_close(fd);
    return (uintptr_t)DEFAULT_ENTRY;
}
